package com.cb.ucenterservice.controller;

import com.cb.servicebase.exception.GuliException;
import com.cb.ucenterservice.entity.UcenterMember;
import com.cb.ucenterservice.service.UcenterMemberService;
import com.cb.ucenterservice.utils.ConstantPropertiesUtils;
import com.cb.ucenterservice.utils.HttpClientUtils;
import com.cb.utils.JwtUtils;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * 微信登录管理
 *
 * @author cb
 * @version 1.0
 * @date 2020/6/28 10:06
 */
@Api(description = "微信登录管理")

@Controller // 此处需要重定向, 所以不能用rest, rest会直接转成json
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    private final UcenterMemberService memberService;

    @Autowired
    public WxApiController(UcenterMemberService memberService) {
        this.memberService = memberService;
    }

    @ApiOperation("登录后的回调方法, 获取扫描人信息")
    @GetMapping("callback")
    public String callback(String code, String state) {
        // 根据code(临时票据)值, 请求微信地址,
        // 获取access_token : 访问凭证,
        // 和openid : 每个微信唯一标识
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String accessTokenUrl = String.format(
                baseAccessTokenUrl,
                ConstantPropertiesUtils.APP_ID,
                ConstantPropertiesUtils.APP_SECRET,
                code);
        try {
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            // 将accessTokenInfo字符串(实际是json)转成map结构
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");

            // 从数据库中尝试获取用户信息
            UcenterMember member = memberService.getOpenIdMember(openid);

            // member是空, 数据库中没有相同数据, 请求微信平台
            if (member == null) {
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid);
                // 拿着access_token, 和openid, 请求微信资源服务器, 获取用户信息
                /**
                 * userInfo:{
                 *   openid : "",     每个用户唯一id
                 *   nickname: "",    昵称
                 *   sex: "",         性别, 1是男
                 *   language: "",    语言
                 *   city: "",        城市
                 *   province: "",    省
                 *   country: "",     国家
                 *   headimgurl: "",  头像url
                 *   privilege: "",
                 *   unionid: ""
                 * }
                 */
                String userInfo = HttpClientUtils.get(userInfoUrl);
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname");
                String avatar = (String) userInfoMap.get("headimgurl");
                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(avatar);
                memberService.save(member);
            }

            //使用jwt根据member对象生成token字符串
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            // 视频中的回调地址, 重定向到我们个人的首页
            return "redirect:http://localhost:3000?token=" + jwtToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "登录失败...");
        }
    }

    @ApiOperation("生成微信扫描的二维码")
    @GetMapping("login")
    public String getWxCode() {
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 对redirectUrl进行URLEncoder编码
        String redirectUrl = ConstantPropertiesUtils.REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = String.format(
                baseUrl,
                ConstantPropertiesUtils.APP_ID,
                redirectUrl,
                "atguigu");

        // 通过重定向, 直接访问微信地址
        return "redirect:" + url;
    }
}
